# !/usr/bin/env python
# -*- coding: utf-8 -*-
from pprint import pprint

from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt

from mytest.models import Department
from mytest.utils.forms import DepartmentModelForm

@csrf_exempt
def data_list(request):
    """ 展示列表 """

    if request.method == "GET":
        return render(request, "mytest/data_list.html")


    # 1. 查询关键字处理
    search = {}
    keyword = request.GET.get('keyword', "")

    from mytest.utils.pagination import Pagination

    queryset = Department.objects.all().order_by('-id').filter(**search).values()

    pprint(list(queryset))

    # 如果不是get方法则：
    reponse = {
        "status": True,
        "name": "张三",
        "data": {
            "rows": list(queryset)
        }
    }

    return JsonResponse(reponse)

    # # 1. 查询关键字处理
    # search = {}
    # keyword = request.GET.get('keyword', "")
    #
    # from mytest.utils.pagination import Pagination
    #
    # queryset = Department.objects.all().order_by('-id').filter(**search)
    #
    # form = DepartmentModelForm()
    #
    # parameter = {
    #     "request": request,
    #     "queryset": queryset,
    #     "form": form,
    #     "page_size": 10
    # }
    #
    # data = Pagination(**parameter).get_content()
    #
    # # 添加form是为了使用它的表单备注来当前端数据的列头名
    # form = DepartmentModelForm()
    # data['form'] = form
    # data['keyword'] = keyword  # 临时加个搜索关键字看效果
    #
    # response = {
    #     "code": 200,
    #     "msg": "操作成功",
    #     "data": data
    # }
    #
    #
    # # get请求返回响应
    # return render(request, "mytest/data_list.html", response)




def add_list(request):
    """ 添加数据 """

    form = DepartmentModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        result = {
            "status": True,
        }
        return JsonResponse(result)

    # print("错误返回")
    return JsonResponse({"status": False, "error": form.errors})


def delete_list(request, nid):
    """ 删除数据 """
    # print(nid)
    Department.objects.filter(id=nid).delete()
    return redirect('mytest:data_list')


def edit_list(request, nid):
    """ 编辑数据 """

    if request.method == "GET":
        row_data = Department.objects.get(id=nid)
        print(row_data.id)
        print(nid)
        return render(
            request,
            "mytest/data_edit.html",
            {
                'nid':  nid,
                "edit_data": row_data
            }
        )

    # 获取用户修改后的值
    edit_end_data = request.POST.get('title')

    # 根据ID进行修改
    Department.objects.filter(id=nid).update(title=edit_end_data)

    # 重定向回部门列表
    return redirect('mytest:data_list')


